package org.example.demoarticle.LoginCheckInterceptor;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.demoarticle.pojo.ResultByLogin;
import org.example.demoarticle.util.jwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletRequest req= request;
        HttpServletResponse res= response;

        String url=req.getRequestURL().toString();
        log.info("请求的URL：",url);

        if(url.contains("login")) {
            log.info("登陆操作 放行");
            return true;
        }

        String s=req.getHeader("Authorization");
        String jwt="";
        if(s!=null) {
            jwt=s.substring("Bearer ".length()).trim();
        }
        if(!StringUtils.hasLength(jwt)) {
            log.info("请求头为空 返回未登录错误信息");
            ResultByLogin ret=ResultByLogin.error("未登录!!");
            String notLogin= JSONObject.toJSONString(ret);
            res.getWriter().write(notLogin);
            return false;
        }

        try {
            jwtUtil.parseJwt(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析令牌失败");
            ResultByLogin ret=ResultByLogin.error("未登录!!");
            String notLogin= JSONObject.toJSONString(ret);
            res.getWriter().write(notLogin);
            return false;
        }

        log.info("放行");
        return true;
    }

}
